export default {
    name: "EmployeeForm",
    props: {
        value: Boolean, // 对话框显示与隐藏
        title: String,  //标题
        formData: Object, // 表单数据
        companyOptions: Array, //收公司下拉选项
    },
    data() {
        return {
            //表单数据
            formModel: this.getDefaultFormData(),
            // 表单验证规则
            formRules: {
                name: [
                    {required: true, message: '请输入员工姓名', trigger: 'blur'},
                    {min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur'}
                ],
                age: [
                    {required: true, message: '请输入年龄', trigger: 'blur'},
                    {type: 'number', min: 18, max: 100, message: '年龄必须在18到100岁之间', trigger: 'blur'}
                ],
                employmentDate: [
                    {required: true, message: '请选择入职日期', trigger: 'change'}
                ],
                companyId: [
                    {required: true, message: '请选择所属公司', trigger: 'change'}
                ],
                employed: [
                    {required: true, message: '请选择在职状态', trigger: 'change'}
                ]
            },
            // 提交状态
            submitting: false,
        }
    },
    watch: {
        formData: {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    this.formModel = {...this.getDefaultFormData(), ...newVal};
                }
            }
        }
    },
    computed: {
        visible: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            }
        }
    },
    methods: {
        //初始化空对象
        getDefaultFormData() {
            return {
                name: '',
                age: null,
                employmentDate: '',
                employed: true,
                companyId: null
            };
        },
        //提交表单
        submitForm() {
            this.$refs.employeeForm.validate(valid => {
                if (valid) {
                    this.submitting = true
                    // 提交数据到父组件
                    this.$emit('submit', this.formModel)
                }
            })
        },
        //重置表单
        resetForm() {
            this.$refs.employeeForm.resetFields()
            this.$emit('reset')
        },
    }
}
